package database

import (
	"gin-xorm/models"
	"strconv"
	"time"

	"github.com/dgrijalva/jwt-go"
)

var jwtkey = []byte("dayd fsdfs")

type Claims struct {
	UserId int
	jwt.StandardClaims
}

func ReleaseToken(user models.User) (string, error) {

	expirationTime := time.Now().Add(7 * 24 * time.Hour)
	claims := &Claims{
		UserId: user.Id,
		StandardClaims: jwt.StandardClaims{
			ExpiresAt: expirationTime.Unix(),
			IssuedAt:  time.Now().Unix(),
			Issuer:    "dayd",
			Subject:   "user token",
		},
	}
	token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
	tokenString, err := token.SignedString(jwtkey)
	if err != nil {
		return "", err
	}
	// r.ExpireAt()
	_, err = r.SetEx(strconv.Itoa(user.Id), 7*24*60*60, tokenString)

	if err != nil {
		rLog.Debug("redis写入失败")
	}
	return tokenString, nil
}

func ParseToken(tokensting string) (*jwt.Token, *Claims, error) {

	claime := &Claims{}
	token, err := jwt.ParseWithClaims(tokensting, claime, func(token *jwt.Token) (i interface{}, err error) {
		return jwtkey, nil
	})
	return token, claime, err
}
